package com.ds.lens.data.service.dao.mybatis;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.util.Map;

/**
 * Description:
 *
 * @author WeiShaoying
 * @date 2019-11-04
 */
@MappedTypes({Map.class})
public class MapTypeHandler implements TypeHandler<Map> {
    @Override
    public void setParameter(PreparedStatement ps, int i, Map parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setNull(i, Types.VARCHAR);
        } else {
            ps.setString(i, JSONObject.toJSONString(parameter));
        }
    }

    @Override
    public Map getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return JSONObject.parseObject(value, Map.class);
    }

    @Override
    public Map getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return JSONObject.parseObject(value, Map.class);
    }

    @Override
    public Map getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return JSONObject.parseObject(value, Map.class);
    }
}
